/*
	http://davidwalsh.name/mootools-nextprev
*/

var NextPrev = new Class({
			Implements: [Options,Events],
			options: {
				baseEvent: 'keyup',
				eventContainer: document,
				eventCheckNext: function(e){
					return true;
				},
				eventCheckPrevious: function(e){ 
					return true;
				},
				onLoad: $empty,
				onNext: $empty,
				onPrevious: $empty,
				startIndex: 0
			},
			initialize: function(collection,options) {
				this.setOptions(options);
				this.collection = $$(collection);
				if(this.options.container == document) this.options.container = document.body;
				this.index = this.options.startIndex;
				if(this.options.baseEvent) {
					$(this.options.eventContainer).addEvent(this.options.baseEvent,function(e) {
						if(this.options.eventCheckNext(e)) {
							this.move.bind(this)('next');
						}
						else if(this.options.eventCheckPrevious(e)) {
							this.move.bind(this)('previous');
						}
					}.bind(this));
				}
				this.fireEvent('load',[this.collection[this.index]]);
			},
			move: function(norp) {
				var previous = this.index;
				switch($type(norp)) {
					case 'string':
						var ev = 'next';
						if(norp == 'next') {
							var plus = this.index + 1;
							this.index = this.collection[plus] ? plus : 0;
						}
						else {
							var minus = this.index - 1;
							this.index = this.collection[minus] ? minus : this.collection.length-1;
							ev = 'previous';
						}
						this.fireEvent(ev,[this.collection[this.index],this.collection[previous]]);
						break;
					case 'element':
						this.index = this.collection.indexOf(norp) || 0;
						break;
					default:
						this.index = norp;
						break;
				}
				this.fireEvent('change',[this.collection[this.index],this.collection[previous]]);
				return this;
			}
		});
